/**
 * @file    instructions.c
 * @author  Thomas Di'Meco and Matthieu Maugard
 * @brief   Instructions defines and utilities
 */

#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "instructions.h"


// Private members
void strtoupper (char * str);


/**
 * Instructions strings. String equivalent for each instruction in
 * the instructions enum (that must be in the same order)
 */
const char * instruction_str[INSTRUCTION_NUMBER] =
{
    "LOAD",  // Load
    "STORE", // Store
    "ADD",   // Add
    "SUB",   // Sub
    "JMP",   // Jump
    "JEQ",   // Jump if equal
    "CALL",  // Call
    "RET",   // Return
    "PUSH",  // Push
    "POP",   // Pop
    "HALT"   // Halt
};


/**
 * Returns the instruction equivalent to the given string
 * @param str The instruction string to parse
 * @return The instruction equivalent (see instructions enum)
 *         or -1 if the instruction does not exist
 */
int16_t get_instruction (char * str)
{
    // Upper case the given string
    strtoupper(str);

    // Search for the instruction equivalent of str
    int i;

    for (i = 0; i < INSTRUCTION_NUMBER; i++)
        if (!strcmp(str, instruction_str[i]))
            return i;

    // Returns -1 if the instruction does not exist
    return -1;
}


/**
 * Change the case of the given string to upper case
 * @param str The string
 */
void strtoupper (char * str)
{
    int i = 0;

    while (str[i])
    {
        str[i] = toupper(str[i]);
        i++;
    }
}
